# 连接数据库
import pymysql, json

def get_area(parent_code):
    conn = pymysql.Connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='123456',
        db='homemall',
        charset='utf8',
    )
    # print(conn)
    # 获取游标
    my_cursor = conn.cursor()
    # 准备SQL
    sql = 'SELECT * FROM tb_area where parent_code = %s'
    # 准备插入的数据
    values = (parent_code,)
    # 执行SQL
    my_cursor.execute(sql,values)
    # 获取所有记录
    rs = my_cursor.fetchall()
    # 关闭连接
    conn.close()
    addresses = []
    for address in rs:
        addresses.append({
            'region_code': address[0],
            'region_name': address[1],
            'parent_code': address[2],
        })
    return addresses;
provinces = get_area(0)
area_list = []

for province in provinces:
    area_list.append(province)
    # print(province)
    cities = get_area(province.get('region_code'))
    for city in cities:
        # print(f'\t{city}')
        province['cities'] = cities
        counties = get_area(city.get('region_code'))
        city['counties'] = counties
for province in area_list:
    print(province)
with open(file='tb_area.json', mode='w', encoding='utf-8') as f:
    json.dump(area_list, f, ensure_ascii=False)
print('写入完成')
